package com.googlecode.continuity.plugin.rating.server.service;

import java.util.List;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.googlecode.continuity.core.client.ContinuityUser;
import com.googlecode.continuity.core.client.Message;

/**
 * RatingServiceHibernate
 * <p/>
 * TODO: this class is highly inefficient
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class RatingServiceHibernate extends HibernateDaoSupport implements RatingService {
// ------------------------ INTERFACE METHODS ------------------------

// --------------------- Interface RatingService ---------------------

  public void setRating(ContinuityUser user, Message message, int rating) {
    setRating(user.getId(), message.getId(), rating);
  }

  public void setRating(int userId, int messageId, int rating) {
    List ratings =
        getHibernateTemplate().find("from Rating where messageId = ? and userId = ?", new Object[]{messageId, userId});
    if (ratings.size() == 0) {
      Rating rat = new Rating();
      rat.setMessageId(messageId);
      rat.setUserId(userId);
      rat.setRating(rating);
      getHibernateTemplate().save(rat);
      return;
    }
    Rating rat = (Rating) ratings.get(0);
    rat.setRating(rating);
    getHibernateTemplate().update(rat);
  }

  public int getRating(ContinuityUser user, Message message) {
    return getRating(user.getId(), message.getId());
  }

  public int getRating(int userId, int messageId) {
    List ratings =
        getHibernateTemplate().find("from Rating where messageId = ? and userId = ?", new Object[]{messageId, userId});
    if (ratings.size() == 0) {
      return 0;
    }
    return ((Rating) ratings.get(0)).getRating();
  }

  public float getRatingAverage(Message message) {
    return getRatingAverage(message.getId());
  }

  public float getRatingAverage(int messageId) {
    List rating = getHibernateTemplate().find(
        "select case count(*) when 0 then 0.0 else (sum(rating)/count(*)) end from Rating where messageId = ?",
        messageId);
    return ((Double) rating.get(0)).floatValue();
  }

  public int getRatingCount(int messageId) {
    return DataAccessUtils
        .intResult(getHibernateTemplate().find("select count(*) from Rating where messageId = ?", messageId));
  }

  public int getRatingCount(Message message) {
    return getRatingCount(message.getId());
  }
}
